#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE 128 
void PrintCommandLine()
{
  char CommandLine[SIZE];
  const char* Name = getenv("USER")==NULL?"None":getenv("USER");
  const char* HostName = getenv("HOSTNAME")==NULL?"None":getenv("HOSTNAME");
  const char* Pwd = getenv("PWD")==NULL?"None":getenv("PWD");
  snprintf(CommandLine,sizeof(CommandLine),"[%s@%s %s]>",Name,HostName,Pwd);
  printf("%s",CommandLine);
  fflush(stdout);


}
  char* GetCommand()
{
  char* Command=(char*)malloc(SIZE);
  if(Command==NULL)
  {
    printf("shortage of memory");
    exit(11);
  }
  char* s=fgets(Command,SIZE-1,stdin);
  if(s==NULL) return NULL;
  Command[strlen(Command)-1]='\0';
  return Command;
}
void  DealCommand(char* Command)
{
  //分割命令 
  char* MArgv[SIZE]; memset(MArgv,0,sizeof(MArgv));
  int i =1;
  MArgv[0]=strtok(Command," ");
  if(MArgv[0]!=NULL)
  while((MArgv[i++]=strtok(NULL," ")));
  //执行命令
  
  pid_t id =fork();
  if(id == 0)
  {
    execvp(MArgv[0],MArgv);
	printf("1\n");
   
    exit(errno);
  }
  else if(id<0)
  {
    printf("new process error");
    exit(44);
  }
  else
  {
    int status=0;
    pid_t pid=waitpid(id,&status,0);
    if(pid<0)
    {
      printf("wait error");
      exit(33);
    }
    else
    {
     int LastErrorCode = WEXITSTATUS(status);
      if(LastErrorCode!=0)
        printf("%s:%s error code:%d\n",MArgv[0],strerror(LastErrorCode),LastErrorCode);
    }
    
  }
}



int main()
{
  size_t  Quit = 1;
  while(Quit)
  {
    //打印命令行
    PrintCommandLine();
    //获取用户命令
  char* Command=GetCommand();
   //对命令进行处理
   if(Command==NULL) 
   {
     printf("Command error!");
     exit(66);
    }
  
   DealCommand(Command);
  }
}
